import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义ｊｗｔ认证
    :param token:
    :param user:
    :param request:
    :return:
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username,
    }


# def get_user_by_account(account):
#     """
#      根据帐号获取user对象
#     :param account: 账号，可以是用户名，也可以是手机号
#     :return: User对象 或者 None
#     """
#     try:
#         if re.match('^1[3-9]\d{9}$', account):
#             # 手机号登入
#             user = User.objects.get(mobile=account)
#         else:
#             # 用户名登入
#             user = User.objects.get(username=account)
#
#     except User.DoesNotExist:
#         return None
#     else:
#         return user
#
#
# # 自定义用户名或手机号认证
# class UsernameMobileAuthBackend(ModelBackend):
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         user = get_user_by_account(username)
#         if user is not None and user.check_password(password):
#             return user
class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        # 匹配手机格式
        try:
            if re.match(r'^1[3-9]\d{9}$', username):

                user = User.objects.get(mobile=username)

            else:
                user = User.objects.get(username=username)
        except:
            user = None
        # 密码校验
        if user is not None and user.check_password(password):
            return user
        return user
